wx.cloud.init()
const db = wx.cloud.database();
var time = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    info: {}, //用户信息对象
    imagetemp: [], //图片列表
    videolist: [], //视频列表
    isSwitch: false, //查看图片是否需要密码
    bodyheight: ['身高:保密', '150CM', '155CM', '158CM', '160CM', '162CM', '163CM', '164CM', '165CM', '168CM', '170CM', '172CM', '173CM', '175CM', '180CM', '182CM', '185CM', '187CM', '188CM', '190CM', '195CM'],
    bodyheightValue: [0, 150, 155, 158, 160, 162, 163, 164, 165, 168, 170, 172, 173, 175, 180, 182, 185, 187, 188, 190, 195],
    bodyheight_ind: 0,
    bodyweight: ['体重:保密', '45公斤', '48公斤', '50公斤', '52公斤', '54公斤', '56公斤', '58公斤', '60公斤', '65公斤', '68公斤', '70公斤', '72公斤', '75公斤', '77公斤', '80公斤', '82公斤', '85公斤', '88公斤', '90公斤', '92公斤', '95公斤', '100公斤'],
    bodyweightValue: [0, 45, 48, 50, 52, 54, 56, 58, 60, 65, 68, 70, 72, 75, 77, 80, 82, 85, 88, 90, 92, 95, 100],
    bodyweight_ind: 0,
    sex: ['女', '男'],
    sex_ind: 0,
    age: ['请选择年龄', '18岁', '19岁', '20岁', '21岁', '22岁', '23岁', '24岁', '25岁', '26岁', '27岁', '28岁', '29岁', '30岁', '31岁', '32岁', '33岁', '34岁', '35岁', '36岁', '37岁', '38岁', '39岁', '40岁', '41岁', '42岁', '43岁', '44岁', '45岁', '46岁', '47岁', '48岁', '49岁', '50岁', '51岁', '52岁', '53岁', '54岁', '55岁', '56岁', '57岁', '58岁', '59岁', '60岁', '61岁', '62岁', '63岁', '64岁', '65岁', '66岁', '67岁', '68岁', '69岁', '70岁'],
    ageValue: [0, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,  61, 62, 63, 64, 65, 66, 67, 68, 69, 70],
    age_ind: 0,
    education: ['学历:保密', '无文化', '小学', '初中', '高中', '中专', '大专', '大学', '硕士', '博士'],
    education_ind: 0,
    family: ['家庭:保密', '独生子女', '兄弟2人', '兄妹2人', '兄弟3人', '兄妹3人', '兄弟4人', '兄妹4人'],
    family_ind: 0,
    marriage: ['未婚', '离异', '丧偶'],
    marriage_ind: 0,
    houses: ['购房:保密', '1套房', '2套房', '3套房', '4套房', '5套房', '大于5套房', ],
    housesValue: [0, 1, 2, 3, 4, 5, 6],
    houses_ind: 0,
    region: ['安徽省', '蚌埠市', '龙子湖区'],
    customItem: '全部',
    istip_name: false,
    isfoucs_name: false,
    istip_age: false, //用户没有填写的时候给出红色边框    
    istip_phones: false,
    isfoucs_phones: false,
    istip_claim: false,
    isfoucs_claim: false,
    admin_authority: '红娘',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var admin_openid = wx.getStorageSync('admin_openid')
    if (typeof (admin_openid) == "undefined" || admin_openid == 0) {
      wx.reLaunch({
        url: '/pages/admin/admin',
      })
    } else {
      if (typeof (options.id) == "undefined") {
        console.log('ID为空')
      } else {
        this.getData(options.id)
      }
    }


  },
  getData: function (id) {
    /**获取用户原有信息 */
    console.log('getdata被执行 id:', id)
    db.collection('user').doc(id).get()
      .then(res => {
        console.log('用户信息:', res)
        this.setData({
          info: res.data,
          imagetemp: res.data.image,
          videolist: typeof (res.data.video) == "undefined" ? [] : res.data.video, //视频地址,不能是undefined
          isSwitch: res.data.imageispwd,
          bodyheight_ind: res.data.bodyheight_ind,
          bodyweight_ind: res.data.bodyweight_ind,
          sex_ind: res.data.sex_ind,
          age_ind: res.data.age_ind,
          education_ind: res.data.education_ind,
          family_ind: res.data.family_ind,
          marriage_ind: res.data.marriage_ind,
          houses_ind: res.data.houses_ind,
          region: res.data.address,
          admin_authority: wx.getStorageSync('authority') //红娘还是管理员
        })
      })
  },
  istip: function (e) {
    //关闭红色提示框,传递一个提示框的名称
    let tip = e.target.dataset.name
    this.setData({
      [tip]: false, //关闭红色提示框
    })

  },
  formSubmit: function (e) {
    /**提交表单 */
    var name = e.detail.value.name; //姓名
    var bodyheight = this.data.bodyheightValue[this.data.bodyheight_ind]; //身高
    var bodyheight_ind = this.data.bodyheight_ind; //身高值,用在编辑中的默认选中记录
    var bodyweight = this.data.bodyweightValue[this.data.bodyweight_ind]; //体重
    var bodyweight_ind = this.data.bodyweight_ind; //体重,用在编辑中的默认选中记录
    var sex = this.data.sex[this.data.sex_ind]; //性别
    var sex_ind = this.data.sex_ind; //性别
    var age = this.data.ageValue[this.data.age_ind]; //年龄
    var age_ind = this.data.age_ind; //年龄
    var education = this.data.education[this.data.education_ind]; //学历
    var education_ind = this.data.education_ind; //学历
    var family = this.data.family[this.data.family_ind]; //家庭成员
    var family_ind = this.data.family_ind; //家庭成员
    var marriage = this.data.marriage[this.data.marriage_ind]; //婚姻状态
    var marriage_ind = this.data.marriage_ind; //婚姻状态
    var houses = this.data.housesValue[this.data.houses_ind]; //购房状态
    var houses_ind = this.data.houses_ind; //购房状态
    var phones = e.detail.value.phones; //红娘电话
    var phone = e.detail.value.phone; //客户电话
    var claim = e.detail.value.claim; //择偶条件
    var directions = e.detail.value.directions; //红娘说
    var imageispwd = this.data.isSwitch; //图片是否需要密码
    var imagepwd = e.detail.value.imagepwd; //查看图片密码
    var address = this.data.region; //用户的地址
    var pengyouquan=this.data.info.pengyouquan //朋友圈


    if (typeof (name) == "undefined" || name == 0) {
      wx.showToast({
        title: '姓名不能为空',
        icon: 'none'
      })
      this.setData({
        istip_name: true,
        isfocus_name: true
      })
      return;
    }



    // if (typeof(phone) == "undefined" || phone == 0) {
    //   wx.showToast({
    //     title: '客户电话不能为空',
    //     icon: 'none'
    //   })
    //   return;
    // }

    // var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    // if (!myreg.test(phone)) {
    //   wx.showToast({
    //     title: '客户手机号码不正确',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return;
    // }

    if (age == 0) {
      wx.showToast({
        title: '年龄必须填写哟',
        icon: 'none'
      })
      this.setData({
        istip_age: true,
      })
      return;
    }

    if (typeof (phone) == "undefined" || phone == 0) {
      phone = '18800000000'
    }

    if (typeof (phones) == "undefined" || phones == 0) {
      wx.showToast({
        title: '红娘电话不能为空',
        icon: 'none'
      })
      this.setData({
        istip_phones: true,
        isfocus_phones: true
      })
      return;
    }

    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    if (!myreg.test(phones)) {
      wx.showToast({
        title: '对外红娘手机号码不正确',
        icon: 'none',
        duration: 2000
      })
      this.setData({
        istip_phones: true,
        isfocus_phones: true
      })
      return;
    }

    if (typeof (claim) == "undefined" || claim == 0) {
      wx.showToast({
        title: '择偶标准不能为空',
        icon: 'none'
      })
      this.setData({
        istip_claim: true,
        isfocus_claim: true
      })
      return;
    }

    if (claim.length < 6) {
      wx.showToast({
        title: '择偶标准最少6个字',
        icon: 'none'
      })
      this.setData({
        istip_claim: true,
        isfocus_claim: true
      })
      return;
    }




    /**准备上传图片和表单 */
    this.uploadimg({
      id: this.data.info._id, //用户信息id
      path: this.data.imagetemp, //这里是图片路径
      name: name, //姓名
      bodyheight: bodyheight, //身高
      bodyheight_ind: bodyheight_ind,
      bodyweight: bodyweight, //体重
      bodyweight_ind: bodyweight_ind,
      sex: sex, //性别
      sex_ind: sex_ind,
      age: age, //年龄
      age_ind: age_ind,
      education: education, //学历
      education_ind: education_ind,
      family: family, //家庭成员
      family_ind: family_ind,
      marriage: marriage, //婚姻状态
      marriage_ind: marriage_ind,
      houses: houses, //购房状态
      houses_ind: houses_ind,
      phones: phones, //红娘电话
      phone: phone, //客户电话
      claim: claim, //择偶条件
      directions: directions, //红娘说
      imageispwd: imageispwd, //查看图片是否需要密码?
      imagepwd: imagepwd, //查看图片密码
      address: address, //用户的地址
      hico: [], //必须为空
      video: this.data.videolist,
      pengyouquan:pengyouquan
    });



  },
  uploadimg: function (data) {
    /**增加表单数据到数据库 */
    console.log('data:', data)
    var that = this,
      hico = data.hico.length > 0 ? data.hico : [], //当前上传的哪张图片
      i = data.i ? data.i : 0, //当前上传的哪张图片
      success = data.success ? data.success : 0, //上传成功的个数
      fail = data.fail ? data.fail : 0; //上传失败的个数
    if (data.path.length == 0) { //该用户没有上传图片
      that.uploadData(data)
    } else { //图片列表不等于空
      console.log('i:', i, data.path.length)
      console.log('文件路径:', data.path[i])
      //不包含的情况下有可能是undefined,所以要对他处理,如果是unde则说明用户没有上传新图片,直接更新数据库即可

      if (i == data.path.length) { //当图片传完时，停止调用 ,
        that.uploadData(data)
      } else { //图片没有在最后一个,准备上传
        if (data.path[i].indexOf('cloud://') > -1) { //如果已经是上传过的图片,则直接把路径增加到hico中
          //console.log('包含')
          hico.push(data.path[i])
          data.hico = hico
          i++;
          data.i = i;
          that.uploadimg(data);
        } else { //如果没包含cloud则说明是新上传的,上传图片
          //console.log('不包含')
          wx.showLoading({
            title: '正在上传图片',
          })

          wx.cloud.uploadFile({
            cloudPath: `user/${time.formatTime(new Date)}/${Math.floor(Math.random() * 100000000)}.jpg`, // 上传至云端的路径
            filePath: data.path[i], // 临时文件路径
            success: res => {
               console.log('成功返回:',res)
              if (res.statusCode == 2) {
                success++; //图片上传成功，图片上传成功的变量+1
              } else {
                fail++; //图片上传失败，图片上传失败的变量+1
              }
            },
            fail: err => {
              console.log('失败返回:', err)
              fail++; //图片上传失败，图片上传失败的变量+1
            },
            complete: img => {
             console.log('都执行返回:', i, img)
              if (img.statusCode >= 200) { //把上传成功的返回增加到 data.hico去
                hico.push(img.fileID)
                data.hico = hico
              }
              i++;
              data.i = i;
              data.success = success;
              data.fail = fail;
              that.uploadimg(data);

            }
          }) //云文件上传结束
        } //判断是否需要上传文件的结束

      } //判断是否在最后一个图片结束

    } //判断图片列表是否为空的结束
  },
  uploadData: function (data) {
    /**把信息增加到数据库 */
    var that = this
    console.log('更新到数据库被执行', data)


    if (that.data.admin_authority == '管理员') {
      wx.cloud.callFunction({
        name: 'edit',
        data: {
          id:data.id,
          name: data.name, //姓名
          bodyheight: data.bodyheight, //身高
          bodyheight_ind: parseInt(data.bodyheight_ind),
          bodyweight: data.bodyweight, //体重
          bodyweight_ind: parseInt(data.bodyweight_ind),
          sex: data.sex, //性别
          sex_ind: parseInt(data.sex_ind),
          age: data.age, //年龄
          age_ind: parseInt(data.age_ind),
          education: data.education, //学历
          education_ind: parseInt(data.education_ind),
          family: data.family, //家庭成员
          family_ind: parseInt(data.family_ind),
          marriage: data.marriage, //婚姻状态
          marriage_ind: parseInt(data.marriage_ind),
          houses: data.houses, //购房状态
          houses_ind: parseInt(data.houses_ind),
          phones: data.phones, //红娘电话
          phone: data.phone, //客户电话
          claim: data.claim, //择偶条件
          directions: data.directions, //红娘说
          imageispwd: data.imageispwd, //查看图片是否需要密码?
          imagepwd: data.imagepwd, //查看图片的密码
          address: data.address, //用户的地址
          image: data.hico, //图片列表
          video: data.video, //视频列表
          pengyouquan:data.pengyouquan//朋友圈
        }
      }).then(res => {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '管理员更新成功',
          success(res) {
            wx.reLaunch({
              url: '../userlist/userlist',
            })
          }
        })

      })
    } else {

      db.collection('user').doc(data.id).update({
        data: {
          name: data.name, //姓名
          bodyheight: data.bodyheight, //身高
          bodyheight_ind: parseInt(data.bodyheight_ind),
          bodyweight: data.bodyweight, //体重
          bodyweight_ind: parseInt(data.bodyweight_ind),
          sex: data.sex, //性别
          sex_ind: parseInt(data.sex_ind),
          age: data.age, //年龄
          age_ind: parseInt(data.age_ind),
          education: data.education, //学历
          education_ind: parseInt(data.education_ind),
          family: data.family, //家庭成员
          family_ind: parseInt(data.family_ind),
          marriage: data.marriage, //婚姻状态
          marriage_ind: parseInt(data.marriage_ind),
          houses: data.houses, //购房状态
          houses_ind: parseInt(data.houses_ind),
          phones: data.phones, //红娘电话
          phone: data.phone, //客户电话
          claim: data.claim, //择偶条件
          directions: data.directions, //红娘说
          imageispwd: data.imageispwd, //查看图片是否需要密码?
          imagepwd: data.imagepwd, //查看图片的密码
          address: data.address, //用户的地址
          image: data.hico, //图片列表
          video: data.video //视频列表
        }
      }).then(res => {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '更新成功',
          success(res) {
            wx.reLaunch({
              url: '../userlist/userlist',
            })
          }
        })

      })
    }

  },
  bodyheight: function (e) {
    /**选择了身高 */
    console.log(e.detail.value)
    this.setData({
      bodyheight_ind: e.detail.value
    })
  },
  bodyweight: function (e) {
    /**选择了体重 */
    console.log(e.detail.value)
    this.setData({
      bodyweight_ind: e.detail.value
    })
  },
  sex: function (e) {
    /**选择了性别 */
    console.log(e.detail.value)
    this.setData({
      sex_ind: e.detail.value
    })
  },
  age: function (e) {
    /**选择了年龄 */
    console.log(e.detail.value)
    this.setData({
      age_ind: e.detail.value
    })
  },
  education: function (e) {
    /**选择了学历 */
    console.log(e.detail.value)
    this.setData({
      education_ind: e.detail.value
    })
  },
  family: function (e) {
    /**选择了家庭 */
    console.log(e.detail.value)
    this.setData({
      family_ind: e.detail.value
    })
  },
  marriage: function (e) {
    /**选择了婚姻状态 */
    console.log(e.detail.value)
    this.setData({
      marriage_ind: e.detail.value
    })
  },
  houses: function (e) {
    /**选择了房屋状况 */
    console.log(e.detail.value)
    this.setData({
      houses_ind: e.detail.value
    })
  },

  switchChange: function (e) {
    /**用户选择了图片密码 */
    console.log(e)
    this.setData({
      isSwitch: e.detail.value
    })
  },
  dizhiChange: function (e) {
    /**选择了用户的地址 */
    this.setData({
      region: e.detail.value
    })

  },
  add: function () {
    /**用户选择照片 */
    var that = this;
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        that.setData({
          imagetemp: that.data.imagetemp.concat(res.tempFilePaths)
        })
      }
    })
  },
  imgshow: function (e) {
    //增加报告时用户点击图片显示全屏 
    wx.previewImage({
      current: this.data.imagetemp[e.currentTarget.dataset.index], // 当前显示图片的http链接  
      urls: this.data.imagetemp // 需要预览的图片http链接列表  
    })
  },
  delImg: function (e) {
    //删除图片
    var oldArr = this.data.imagetemp
    let id = e.currentTarget.dataset.id
    var newArr = []
    for (let i = 0; i < oldArr.length; i++) {
      if (i != id) { //不是选中的图片直接增加到新数组
        newArr.push(oldArr[i])
      } else { //反之则删除已存在的图片
        if (oldArr[i].indexOf('cloud://') > -1) { //如果是云图片则删除云图片
          wx.cloud.deleteFile({
            fileList: [oldArr[i]], //要删除的云文件          
          })
        }
      }
    }
    //删除云文件后,需要更新数据库里面的记录
    db.collection('user').doc(this.data.info._id).update({
      data: {
        image: newArr //图片列表
      }
    }).then(res => {
      this.setData({
        imagetemp: newArr
      })
    })



  },

  uploadVideo: function () {
    //上传视频
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success(res) {
        //console.log(res.tempFilePath)

        wx.showLoading({
          title: '正在上传视频',
        })

        wx.cloud.uploadFile({
          cloudPath: `user/${time.formatTime(new Date)}/${Math.floor(Math.random() * 100000000)}.mp4`, // 上传至云端的路径
          filePath: res.tempFilePath, // 临时文件路径
          success: res => {
            wx.hideLoading()
            that.setData({
              videolist: that.data.videolist.concat(res.fileID)
            }, res => {
              console.log('ff', that.data.videolist)
            })
          }
        })

      }
    })
  },
  delvideo: function (e) {
    //删除视频
    var oldArr = this.data.videolist
    let id = e.currentTarget.dataset.id
    var newArr = []
    for (let i = 0; i < oldArr.length; i++) {
      if (i != id) {
        newArr.push(oldArr[i])
      }
    }
    //删除对应的视频文件
    wx.cloud.deleteFile({
      fileList: [oldArr[id]],
      success: res => {
        //删除云文件后,需要更新数据库里面的记录
        db.collection('user').doc(this.data.info._id).update({
          data: {
            video: newArr //视频列表
          }
        }).then(res => {
          this.setData({
            videolist: newArr
          })
        })
      },
      fail: console.error
    })

  },
  switch2Checked:function(e){
    //用户点击了是否允许转发朋友圈
    let pengyouquan="info.pengyouquan"
    this.setData({
      [pengyouquan]:e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})